<?php
/**
 * Created by PhpStorm.
 * User: wdt
 * Date: 2016/4/18
 * Time: 11:52
 */

namespace front\modules\app\controllers;


use common\helpers\ReturnHelper;
use front\controllers\RestBaseController;
use goods\services\ProductService;
use goods\models\Product;
use goods\services\ShopCategoryProductService;
use yii\helpers\ArrayHelper;

class SearchController extends RestBaseController{

    /**
     * 搜索结果商品列表
     * @return string
     */
    public function actionList()
    {
        $data = \Yii::$app->request->get();
        $keyWords = \Yii::$app->request->get('keyWords');
        if (!isset($data['type'])) {
            $data['type'] = 1;
        }

        if (!isset($data['keyWords'])) {
            return ReturnHelper::error('未传递page参数');
        }
        //去除用户输入的空格
        $keyWords = str_replace(' ','',$keyWords);
        if (!isset($data['page'])) {
            return ReturnHelper::error('未传递page参数');
        }
        if (!isset($data['pre-page'])) {
            return ReturnHelper::error('未传递pre-page参数');
        }
        $type = $data['type'];
        $data = ShopCategoryProductService::searchList(['name' => $keyWords,'type' => $type,'product.stock' > 0]);
        $data = ArrayHelper::toArray($data);
        $list = [];

        //根据商品ID获取商品表中正方形列表图
        foreach ($data as $k=>$v) {

            //下架商品不显示
//            $status = ProductService::getStatus($v['pid']);
//            if (!$status) {
//                unset($data[$k]);
//                continue;
//            }

            $img = Product::getThumbList($v['pid']);
            $product = ProductService::ProductInfo($v['pid']);
            $list[$k]['pid'] = $v['pid'];
            $list[$k]['title'] = $product['result']['productInfo']['name'];
            $list[$k]['img'] = $img?$img:$data[$k]['thumb'];
            $list[$k]['img'] = $list[$k]['img'].'@1e_1c_0o_0l_150h_150w_100q.jpg';
            $list[$k]['price'] = ProductService::getPrice($v['pid']);
        }

        //获取查询结果商品的数量，以便app端计算需要分几页
        $total = ShopCategoryProductService::searchCount(['name' => $keyWords,'type' =>$type,'product.stock' > 0]);
        return ReturnHelper::success('success',['total' => $total,'value' => $keyWords,'data' => $list]);
    }

}